﻿//-----------------------------------------------------------------------
// <copyright file="TenantController.cs" company="OOHM PROCESSAMENTO DE DADOS LTDA.">
//     Microsoft Public License (MS-PL) This license governs use of the accompanying
//     software. If you use the software, you accept this license. If you do not
//     accept the license, do not use the software. 1. Definitions The terms "reproduce,"
//     "reproduction," "derivative works," and "distribution" have the same meaning
//     here as under U.S. copyright law. A "contribution" is the original software,
//     or any additions or changes to the software. A "contributor" is any person
//     that distributes its contribution under this license. "Licensed patents"
//     are a contributor's patent claims that read directly on its contribution.
//     2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license,
//     including the license conditions and limitations in section 3, each contributor
//     grants you a non-exclusive, worldwide, royalty-free copyright license to
//     reproduce its contribution, prepare derivative works of its contribution,
//     and distribute its contribution or any derivative works that you create.
//     (B) Patent Grant- Subject to the terms of this license, including the license
//     conditions and limitations in section 3, each contributor grants you a non-exclusive,
//     worldwide, royalty-free license under its licensed patents to make, have
//     made, use, sell, offer for sale, import, and/or otherwise dispose of its
//     contribution in the software or derivative works of the contribution in
//     the software. 3. Conditions and Limitations (A) No Trademark License- This
//     license does not grant you rights to use any contributors' name, logo, or
//     trademarks. (B) If you bring a patent claim against any contributor over
//     patents that you claim are infringed by the software, your patent license
//     from such contributor to the software ends automatically. (C) If you distribute
//     any portion of the software, you must retain all copyright, patent, trademark,
//     and attribution notices that are present in the software. (D) If you distribute
//     any portion of the software in source code form, you may do so only under
//     this license by including a complete copy of this license with your distribution.
//     If you distribute any portion of the software in compiled or object code
//     form, you may only do so under a license that complies with this license.
//     (E) The software is licensed "as-is." You bear the risk of using it. The
//     contributors give no express warranties, guarantees or conditions. You may
//     have additional consumer rights under your local laws which this license
//     cannot change. To the extent permitted under your local laws, the contributors
//     exclude the implied warranties of merchantability, fitness for a particular
// </copyright>
//-----------------------------------------------------------------------
namespace AbstractSaaSTemplate.UI.Web.Controllers{    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Web.Mvc;
    using AbstractSaaSTemplate.Application.Localization;
    using AbstractSaaSTemplate.Application.Mvc;
    using AbstractSaaSTemplate.Domain.Models.Entities;
    using AbstractSaaSTemplate.Domain.Models.Enumerators;
    using AbstractSaaSTemplate.Domain.Repositories;
    using AbstractSaaSTemplate.Domain.Services;
    using AbstractSaaSTemplate.UI.Web.Filters.Actions.Security;
    using AbstractSaaSTemplate.UI.Web.Models.Tenant;

    /// <summary>
    /// Provides HTTP processing logic for the conceptual entity 'Account'
    /// in the '/' module of the application.
    /// </summary>
    public sealed class TenantController : ApplicationController
    {
        /// <summary>
        /// Initializes a new instance of the TenantController class
        /// injecting the services and repositories required for operation.
        /// </summary>
        /// <param name="serviceForMessaging">The service to consume 'Messaging'.</param>
        /// <param name="serviceForMemberships">The service to consume 'Memberships'.</param>
        /// <param name="repositoryForMembership">The service to operate 'Memberships'.</param>
        /// <param name="repositoryForTenancy">The repository for 'Tenancy'.</param>
        public TenantController(
            IMessagingService serviceForMessaging,
            IMembershipService serviceForMemberships,
            IMembershipRepository repositoryForMembership,
            ITenancyRepository repositoryForTenancy)
        {
            this.ServiceForMessaging = serviceForMessaging;
            this.ServiceForMemberships = serviceForMemberships;
            this.RepositoryForMembership = repositoryForMembership;
            this.RepositoryForTenancy = repositoryForTenancy;
        }

        /// <summary>
        /// Gets the service to consume 'Messaging'.
        /// </summary>
        public IMessagingService ServiceForMessaging { get; private set; }
        
        /// <summary>
        /// Gets the service to consume 'Memberships'.
        /// </summary>
        public IMembershipService ServiceForMemberships { get; private set; }

        /// <summary>
        /// Gets the repository to operate 'Memberships'.
        /// </summary>
        public IMembershipRepository RepositoryForMembership { get; private set; }

        /// <summary>
        /// Gets the repository to operare 'Tenancy'.
        /// </summary>
        public ITenancyRepository RepositoryForTenancy { get; private set; }

        /// <summary>
        /// GET: /Tenant/
        /// Provides a landing page for the 'Tenant' section of the area.
        /// </summary>
        /// <returns>Returns a view containing a landing page</returns>
        [HttpGet]
        public ActionResult Index()
        {
            return this.Result();
        }

        /// <summary>
        /// GET: /Tenant/ListTenants
        /// Provides a page containing all tenants available in the system
        /// for the 'Tenant' section of the area.
        /// </summary>
        /// <returns>Returns a view containing a listing page</returns>
        [HttpGet]
        [FeatureAuthorization(
            AccessLevels.Distributor,
            ControlledFeatures.TenantsManagement,
            true)]
        public ActionResult ListTenants()
        {
            var tenants = this.RepositoryForTenancy.Tenants;
            var tenantsAdmins = new Dictionary<Tenant, User>(tenants.Count());

            foreach (var tenant in tenants)
            {
                var tenantAdministrators = this.RepositoryForMembership.GetUsersByTenantIdAndRole(
                    tenant.Id,
                    AccessRoles.Administrator);

                var tenantAdmin = tenantAdministrators.FirstOrDefault();
                if (tenantAdmin != null)
                {
                    tenantsAdmins.Add(
                        tenant,
                        tenantAdmin);
                }
            }

            this.ViewBag.TenantsAdministrators = tenantsAdmins;
            return this.Result(tenants);
        }

        /// <summary>
        /// GET: /Tenant/ResendWelcomeMessage/5
        /// Allows users to re-send the welcome message to tenant administrators.
        /// </summary>
        /// <param name="tenantId">The id of the tenant whose administrator will receive the message.</param>
        [HttpPost]
        public void ResendWelcomeMessage(long tenantId)
        {
            var tenant = this.RepositoryForTenancy.GetTenantById(tenantId);
            var tenantAdmin = this.RepositoryForMembership.GetUsersByTenantIdAndRole(
                tenantId,
                AccessRoles.Administrator).First();
            
            // finally we should send the welcome e-mail to the client.
            // this e-mail shall have instructions for accessing the system.
            var activeUser = this.ServiceForMemberships.ActiveUser;
            var callbackUrl = this.Url.AbsoluteAction("Index", "Dashboard");
            this.ServiceForMessaging.SendWelcomeMessageForTenant(
                activeUser.Id,
                tenant.Id,
                tenantAdmin.Id,
                callbackUrl);
        }

        /// <summary>
        /// GET: /Tenant/CreateOrEdit
        /// GET: /Tenant/CreateOrEdit/5
        /// Provides a create/edit features for the 'Tenant' section of the area.
        /// </summary>
        /// <param name="id">The id which is reference for the entry that you are entity; If null, will cause this action to create a new entry.</param>
        /// <returns>Returns a view containing a landing page</returns>
        [HttpGet]
        [FeatureAuthorization(
            AccessLevels.Distributor,
            ControlledFeatures.TenantsManagement)]
        public ActionResult CreateOrEditTenant(int? id)
        {
            var model = new CreateOrEditTenantForm();

            if (id.HasValue)
            {
                var entity = this.RepositoryForTenancy.GetTenantById(id.Value);
                
                var tenantAdministrators = this.RepositoryForMembership.GetUsersByTenantIdAndRole(entity.Id, AccessRoles.Administrator);
                var tenantAdministrator = null as User;
                if (tenantAdministrators != null)
                {
                    tenantAdministrator = tenantAdministrators.FirstOrDefault();
                }

                if (entity != null)
                {
                    model.CompanyName = entity.CompanyName;
                    model.DisplayName = entity.DisplayName;
                    model.Website = entity.Website;
                    model.KeyOrLocation = entity.Key;

                    model.ContactPhoneAreaCode = entity.ContactPhone.AreaCode;
                    model.ContactPhoneNumber = entity.ContactPhone.Number;
                    model.ContactPhoneExtension = entity.ContactPhone.Extension;

                    model.BillingAddressLine1 = entity.BillingAddress.Line1;
                    model.BillingAddressLine2 = entity.BillingAddress.Line2;
                    model.BillingAddressLine3 = entity.BillingAddress.Line3;
                    model.BillingAddressCity = entity.BillingAddress.City;
                    model.BillingAddressState = entity.BillingAddress.State;
                    model.BillingAddressPostalCode = entity.BillingAddress.PostalCode;
                    model.BillingAddressCountryCode = entity.BillingAddress.CountryCode;

                    model.ContactAddressLine1 = entity.ContactAddress.Line1;
                    model.ContactAddressLine2 = entity.ContactAddress.Line2;
                    model.ContactAddressLine3 = entity.ContactAddress.Line3;
                    model.ContactAddressCity = entity.ContactAddress.City;
                    model.ContactAddressState = entity.ContactAddress.State;
                    model.ContactAddressPostalCode = entity.ContactAddress.PostalCode;
                    model.ContactAddressCountryCode = entity.ContactAddress.CountryCode;

                    if (tenantAdministrator != null)
                    {
                        model.AdministratorFirstName = tenantAdministrator.FirstName;
                        model.AdministratorLastName = tenantAdministrator.LastName;
                        model.AdministratorEmailAddress = tenantAdministrator.EmailAddress;
                    }
                }
            }

            return this.Result(model);
        }

        /// <summary>
        /// POST: /Admin/Tenant/CreateOrEditTenant
        /// POST: /Admin/Tenant/CreateOrEditTenant/5
        /// Processes the user input and try to proceed with the creation or edition of the item.
        /// </summary>
        /// <param name="id">If not null, causes the application to update the enity with the id defined.</param>
        /// <param name="input">The user input parsed into a form (view model) which can be used for easier validation of this data.</param>
        /// <returns>If validation or procedure fails, returns a view with errors loaded into the ModelState; otherwise redirects the user to the action "Index"</returns>
        [HttpPost]
        [FeatureAuthorization(
            AccessLevels.Distributor,
            ControlledFeatures.TenantsManagement)]
        [ValidateAntiForgeryToken]
        public ActionResult CreateOrEditTenant(
            long? id,
            CreateOrEditTenantForm input)
        {
            // we check the basic input and prevents null values for it
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            // we reinforce the model validation
            // this will ensure that the validation is performed
            // even when we are invoking this method from a unit test instead
            // of a HttpRequest.
            if (this.ModelState.IsValid)
            {
                this.TryValidateModel(input);
            }

            // we should validate all the data in the input argument
            // that could not be checked by the DataAnotations in the 'CreateOrEditForm'
            // add all errors using the this.ModelState.AddModelError() method

            /*
            this.ModelState.AddError(
                "Id",
                string.Format(
                    CultureInfo.CurrentCulture,
                    Messages.TheParameterXCannotBeNullOrWhiteSpace,
                    "Id"));
            */

            // we decide whether to proceed or not with the update operation
            // mostly by checking if the this.ModelState.IsValid
            if (this.ModelState.IsValid)
            {
                var tenant = null as Tenant;

                // we attempt to load the existing tenant if any id has
                // been provided. If we find any, we attempt to update
                // the information, instead of creating a new one.
                if (id.HasValue)
                {
                    tenant = this.RepositoryForTenancy.GetTenantById(id.Value);
                }

                // we start defining our tenant entity which will be posted
                // to the services and repositories in order to create a new
                // or updateing our current entity. If tenant is null, it means
                // that we are creating, not editting. so we should start 
                // a complete instance of the complex Entity which will
                // be persisted.
                if (tenant == null)
                {
                    tenant = new Tenant();
                }
                
                // we attempt to parse or resolve the culture from the
                // user input. In case a country is defined, we get the
                // culture from it. Otherwise we just use the currently
                // detected culture
                var country = CountriesAndCultures.AllCountries
                    .Where(d => d.Iso3166Alpha3Key == input.ContactAddressCountryCode)
                    .FirstOrDefault();

                var culture = CultureInfo.CurrentUICulture;

                if (country != null)
                {
                    culture = country.Culture;
                }

                tenant.CompanyName = input.CompanyName;
                tenant.DisplayName = input.DisplayName;
                tenant.Key = input.KeyOrLocation;
                tenant.Website = input.Website;
                tenant.Culture = culture;

                // now we start parsing the address to the tenant's
                // attachments (BillingAddress and then ContactAddress).
                tenant.BillingAddress.Line1 = input.BillingAddressLine1;
                tenant.BillingAddress.Line2 = input.BillingAddressLine2;
                tenant.BillingAddress.Line3 = input.BillingAddressLine3;
                tenant.BillingAddress.City = input.BillingAddressCity;
                tenant.BillingAddress.State = input.BillingAddressState;
                tenant.BillingAddress.CountryCode = input.BillingAddressCountryCode;
                tenant.BillingAddress.PostalCode = input.BillingAddressPostalCode;

                if (input.ContactUsesTheSameAddressAsBilling)
                {
                    tenant.ContactAddress = tenant.BillingAddress;
                }
                else
                {
                    tenant.ContactAddress.Line1 = input.ContactAddressLine1;
                    tenant.ContactAddress.Line2 = input.ContactAddressLine2;
                    tenant.ContactAddress.Line3 = input.ContactAddressLine3;
                    tenant.ContactAddress.City = input.ContactAddressCity;
                    tenant.ContactAddress.State = input.ContactAddressState;
                    tenant.ContactAddress.CountryCode = input.ContactAddressCountryCode;
                    tenant.ContactAddress.PostalCode = input.ContactAddressPostalCode;
                }

                tenant.ContactPhone.AreaCode = input.ContactPhoneAreaCode;
                tenant.ContactPhone.Number = input.ContactPhoneNumber;
                tenant.ContactPhone.Extension = input.ContactPhoneExtension;

                // attempts to update the tenant.
                this.RepositoryForTenancy.AddOrUpdateTenant(tenant);
                
                // now that the tenant already exists, we want to create
                // or update its administrative user. In order to do that
                // we first attempt to retrieve the administrator. If
                // nothing comes back. we create a new user.
                var tenantAdministrator = null as User;
                var tenantAdministrators = this.RepositoryForMembership.GetUsersByTenantIdAndRole(
                    tenant.Id,
                    AccessRoles.Administrator);

                // if any administrator for the tenant was retrieved from
                // the database, we just use it and update it.
                if (tenantAdministrators.Count() != 0)
                {
                    tenantAdministrator = tenantAdministrators.FirstOrDefault();
                }

                // if no tenant administrator has come back, we create a new
                // administrator and generate a new password for it.
                if (tenantAdministrator == null)
                {
                    tenantAdministrator = new User()
                    {
                        AccessLevel = AccessLevels.Tenant,
                        FirstName = input.AdministratorFirstName,
                        LastName = input.AdministratorLastName,
                        EmailAddress = input.AdministratorEmailAddress,
                        ActivatedAt = DateTime.Now,
                        Culture = culture
                    };

                    tenantAdministrator.Credentials.Login = input.AdministratorEmailAddress;
                    tenantAdministrator.Credentials.SetPassword(this.ServiceForMemberships.GenerateNewPassword());
                }

                // attempts to update the user
                this.RepositoryForMembership.AddOrUpdateUser(tenantAdministrator);

                // attempts to associate the user with the role
                this.RepositoryForMembership.AssociateUserWithRole(
                    tenantAdministrator.Id,
                    AccessRoles.Administrator);
                
                // now, we have the tenant and the administrator
                // we have to associate them to each other, which will
                this.RepositoryForMembership.AssociateUserWithTenant(
                    tenantAdministrator.Id,
                    tenant.Id);

                // finally we should send the welcome e-mail to the client.
                // this e-mail shall have instructions for accessing the system.
                var activeUser = this.ServiceForMemberships.ActiveUser;
                var callbackUrl = this.Url.AbsoluteAction("Index", "Dashboard");
                this.ServiceForMessaging.SendWelcomeMessageForTenant(
                    activeUser.Id,
                    tenant.Id,
                    tenantAdministrator.Id,
                    callbackUrl);

                // it was successfull, so we redirect
                // the user to "Default1" > "Index"
                return this.RedirectToAction("ListTenants");
            }

            // we didn't manage to perform the operations
            // therefore we must return the default result
            // with model state information which explains
            // why we couldn't proceed.
            return this.Result(input);
        }
    }
}


